import React, {useEffect, useMemo, useState} from "react";
import {View} from "@tarojs/components";
import {Icon} from "@taroify/icons"
import {orderType} from "@/types";
import {HideLoading, ShowLoading, ToPage} from "@/utils";
import Taro, {useDidShow, usePullDownRefresh, useReachBottom} from "@tarojs/taro"
import OrderList from "@/components/orderList";
import http from "@/request";
import user from "@/store/user";
import {Button, Cell, Field, FloatingBubble, Input, Popup, Tabs} from "@taroify/core";
import PageNav from "@/components/pageNav";
import "./index.scss"
import {useKeyboard} from "taro-hooks";

interface tabType {
    name: string
    value: string,
    key: string,
    visible: string[],
    num: number,
    active?: boolean,
    url: string
}

const pageConfig = {
    pageSize: 10,
    pageNum: 1,
    current: 1,
    total: 0,
    status: 'SeatAssignment'
}
const initFilterVal = {
    bizTeamUsername: '',
    customerPhone: '',
    seatTeamName: ''
}
const Mine: React.FC = () => {
    const [orders, setOrders] = useState<orderType[]>([]);
    const [active, setActive] = useState(0)
    const [tabList, setTabList] = useState<tabType[]>([])
    const [popupOpen, setPopupOpen] = React.useState(false)
    const [popupHeight, setPopupHeight] = useState("30%")
    const {height: keyboardHeight} = useKeyboard()
    const [filterData, setFilterData] = useState({
        ...initFilterVal
    })

    useEffect(() => {
        if (keyboardHeight > 0) {
            setPopupHeight("60%") // 键盘弹出时增加高度
        } else {
            setPopupHeight("30%") // 键盘收起时恢复
        }
    }, [keyboardHeight])

    const allTabs: tabType[] = [{
        name: '团队',
        value: 'SeatAssignment',
        key: 'seatAssignmentOrderNum',
        visible: ['T'],
        num: 0,
        url: '/disp/biz/order/pageForWx',
        active: true
    }, {
        name: '个人',
        value: 'TeamAssignment',
        key: 'teamAssignmentOrderNum',
        visible: ['T', 'F'],
        num: 0,
        url: '/disp/biz/order/pageForWx',
    },{
        name: '改约',
        value: 'OrderReschedule',
        key: 'orderRescheduleOrderNum',
        visible: ['T', 'F'],
        num: 0,
        url: '/disp/biz/order/pageForWx',
    }, {
        name: '未成功',
        value: 'Fail',
        key: 'failOrderNum',
        visible: ['T', 'F'],
        num: 0,
        url: '/disp/biz/order/pageForWx',
    },
    {
        name: '成功',
        value: 'Success',
        key: 'successOrderNum',
        visible: ['T', 'F'],
        url: '/disp/biz/order/pageSuccessOrderForWx',
        num: 0,
    }]

    const refresh = () => {
        initList()
    }
    const initList = () => {
        pageConfig.pageNum = 1
        queryOrderList()
    }

    usePullDownRefresh(() => {
        refresh()
        setTimeout(() => {
            Taro.stopPullDownRefresh();
        }, 500)
    })

    useReachBottom(() => {
        const {pageNum, pageSize, total} = pageConfig
        if (pageNum * pageSize < total) {
            pageConfig.pageNum++
            queryOrderList()
        }
    })

    const [isNoMore, setIsNoMore] = useState('')
    const queryOrderList = (initFilter?: orderType) => {
        setIsNoMore('')
        ShowLoading()
        const {pageNum, pageSize, status} = pageConfig
        const userInfo = user.info
        const filter = userInfo?.teamLeaderFlag === 'T' ? {bizTsamId: userInfo?.teamId} : {userCode: userInfo?.userCode}
        const currentTab = allTabs.find(item => {
            return item.value === pageConfig.status
        })
        http.post(currentTab?.url, {
            ...(initFilter || filterData || {}),
            pageNum,
            pageSize,
            status,
            ...filter
        }).then(res => {
            pageConfig.total = res.data.total
            const {pageNum, pageSize} = pageConfig
            if (pageNum === 1) {
                setOrders((res.data.list || []))
            } else {
                setOrders(prevBills => [...prevBills, ...(res.data.list || [])])
            }
            if (pageNum * pageSize < res.data.total) {
                setIsNoMore('上划加载更多')
            } else if (res.data.total > 5) {
                setIsNoMore('没有更多了')
            } else {
                setIsNoMore('')
            }
        }).finally(() => {
            HideLoading()
            getOrderStatusNum()
        })
    }
    const getOrderStatusNum = () => {
        const params: Partial<{ bizTeamId: string, bizTeamUserCode: string }> = {}
        if (user.info?.teamLeaderFlag === 'T') {
            params.bizTeamId = user.info?.teamId
        } else {
            params.bizTeamUserCode = user.info?.userCode
        }
        http.post('/disp/biz/order/countStatusNum', params).then(res => {
            const showTabs = allTabs.map(item => {
                return {
                    ...item,
                    num: (res.data || {})[item.key]
                }
            }).filter(item => {
                return item.visible.includes(user.info?.teamLeaderFlag || '')
            })
            setTabList(showTabs)
        })
    }
    const tabs = useMemo(() => {
        return tabList.map(item => {
            return {
                ...item,
                name: `${item.name}(${item.num})`
            }
        })
    }, [tabList])

    const tabChange = (val) => {
        pageConfig.status = tabList[val].value
        setActive(val)
        refresh()
    }

    useDidShow(() => {
        queryOrderList()
    });

    const toBatchPage = () => {
        ToPage('/pages/batch-dispatch/index')
    }
    const showFilter = () => {
        setPopupOpen(true)
    }
    const filterChange = (val, key) => {
        setFilterData((prev) => ({
            ...prev,  // 复制旧状态
            [key]: val,  // 更新对应字段
        }));
    }
    const onSure = () => {
        refresh()
        setPopupOpen(false)
    }
    const onReset = () => {
        setFilterData({
            ...initFilterVal
        })
        pageConfig.pageNum = 1
        queryOrderList({...initFilterVal})
        setPopupOpen(false)
    }

    const filterNotEmpty = useMemo(() => {
        return Object.values(filterData).some(val => {
            return val
        })
    }, [filterData])

    return <View className={'page'}>
        <PageNav>
            <View className="order-page-header flex-row flex-item">
                <View className={'page-header-btn'}>
                    <Button variant="text" color="primary" onClick={toBatchPage}>批量派单</Button>
                </View>
                <View className={'page-title flex1'}>订单</View>
            </View>
        </PageNav>
        <View className="tab-box">
            <Tabs value={active} onChange={tabChange}>
                {
                    tabs.map(item => {
                        return (<Tabs.TabPane key={item.value} title={item.name}></Tabs.TabPane>)
                    })
                }
            </Tabs>
        </View>
        <OrderList orderList={orders} onUpdate={refresh}></OrderList>
        <View className="is-end">{isNoMore}</View>
        <FloatingBubble
            axis="xy"
            magnetic="x"
            gap={10}
            className={filterNotEmpty ? '' : 'not-active'}
            icon={<Icon name=" iconfont icon-shaixuan1"/>}
            onClick={showFilter}/>
        <Popup open={popupOpen} rounded placement="bottom" style={{height: popupHeight}}>
            <View className={'filter-popup'}>
                <View className={'title'}>筛选订单</View>
                <View className={'body'}>
                    <Cell.Group inset>
                        <Field label="业务员">
                            <Input
                                placeholder="请输入业务员名称"
                                value={filterData.bizTeamUsername}
                                onChange={(e) => filterChange(e.detail.value, 'bizTeamUsername')}/>
                        </Field>
                    </Cell.Group>
                    <Cell.Group inset>
                        <Field label="手机号">
                            <Input
                                placeholder="请输入客户手机号"
                                value={filterData.customerPhone}
                                onChange={(e) => filterChange(e.detail.value, 'customerPhone')}/>
                        </Field>
                    </Cell.Group>
                    <Cell.Group inset>
                        <Field label="坐席团队">
                            <Input
                                placeholder="请输入坐席团队"
                                value={filterData.seatTeamName}
                                onChange={(e) => filterChange(e.detail.value, 'seatTeamName')}/>
                        </Field>
                    </Cell.Group>
                </View>
                <View className={'footer flex-row'}>
                    <Button shape="round" style={{width: '35%'}} onClick={onReset}>重置</Button>
                    <Button shape="round" color="primary" style={{width: '55%'}} onClick={onSure}>确定</Button>
                </View>
            </View>
        </Popup>
    </View>
}
export default Mine